package fun.ticsmyc.question;

import org.junit.Test;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @author Ticsmyc
 * @package fun.ticsmyc.dataStructure
 * @date 2020-02-13 16:20
 */
public class 栈和队列互相实现 {


    @Test
    public void  testQueue(){
        TwoStackQueue queue = new TwoStackQueue();
        queue.add(1);
        System.out.println(queue.peek());

        queue.add(2);
        System.out.println(queue.peek());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        queue.add(3);
        System.out.println(queue.peek());
    }
    @Test
    public void testStack(){
        TwoQueueStack stack = new TwoQueueStack();
        System.out.println(stack.empty());
        stack.push(1);
        stack.push(2);
        System.out.println(stack.top());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.empty());
    }
}


/**
 * 两个栈组成队列
 */
class TwoStackQueue{

    private Stack<Integer> inputStack;
    private Stack<Integer> outputStack;

    public TwoStackQueue(){
        inputStack=new Stack<>();
        outputStack=new Stack<>();
    }


    public void add(int x ){
        inputStack.push(x);
    }
    public int poll(){
        transferData();
        return outputStack.pop();
    }
    public int peek(){
        transferData();
        return outputStack.peek();
    }

    public void transferData(){
        if(outputStack.empty()){
            while(!inputStack.empty()){
                outputStack.push(inputStack.pop());
            }
        }

    }

    public boolean empty(){
        return inputStack.empty()&&outputStack.empty();
    }

}


/**
 * 两个队列组成栈
 */
class TwoQueueStack{
    private  Queue<Integer> queue1;
    private  Queue<Integer> queue2;

    public TwoQueueStack(){
        queue1= new LinkedList<>();
        queue2=new LinkedList<>();
    }

    public void push(int x){
        queue1.add(x);
    }

    public int pop(){
        while(queue1.size()>1){
            queue2.add(queue1.poll());
        }

        int res =queue1.poll();

        Queue<Integer> temp = queue1;
        queue1=queue2;
        queue2=temp;

        return res;
    }
    public int top(){
        while(queue1.size()>1){
            queue2.add(queue1.poll());
        }
        int res =queue1.poll();
        queue2.add(res);

        Queue<Integer> tmp = queue1;
        queue1=queue2;
        queue2=tmp;

        return res;
    }
    public boolean  empty(){
        return queue1.isEmpty();
    }



}